package cz.fimuni.pa165.frontend;

import cz.fimuni.pa165.backendapi.dto.CarDTO;
import cz.fimuni.pa165.backendapi.dto.EmployeeDTO;
import cz.fimuni.pa165.backendapi.dto.RequestDTO;
import cz.fimuni.pa165.backendapi.dto.ReservationDTO;
import cz.fimuni.pa165.backendapi.facade.ServiceFacade;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Andrej Hraško
 */
@Controller
public class ReservationController {
    
    @Autowired
    private ServiceFacade facade;
    List<CarDTO> cars;
    
    @RequestMapping(value = "/reservations")
    public String reservationHome(Model model) {
        model.addAttribute("cars", cars);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        List<EmployeeDTO> empl = facade.findEmployeeByUsername(name);
        List<ReservationDTO> list3;
        if (empl.get(0).getAuthority().equals("ROLE_USER")){
            list3 = facade.getReservationByEmployee(empl.get(0));
        } else {
            list3 = facade.getAllReservations();
        }
        model.addAttribute("reservations", list3);
        return "reservation/list";
    }
    
    @RequestMapping(value = "/reservationAdd")
    public String addReservation(@RequestParam(value = "input2", required = false) String input2,
            @RequestParam(value = "input3") String input3,
            Model model) {
        
        if (cars==null || cars.size()<1) {
            model.addAttribute("errMessage", "res.errCar");
            return reservationHome(model);
        }
        
        java.util.Date utilDate = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        try {
            utilDate = dateFormat.parse(input3);
        } catch (Exception ex) {
            model.addAttribute("errMessage", "employeelist.errorMessage3");            
        }
        if (utilDate == null) {
            model.addAttribute("errMessage", "res.errDate");
            return reservationHome(model);
        }
        
        ReservationDTO res = new ReservationDTO();
        
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        List<EmployeeDTO> empl = facade.findEmployeeByUsername(name);
        res.setEmployee(empl.get(0));
        
        Long carId = Long.parseLong(input2);
        CarDTO car = facade.find(carId);
        if(!car.getAvailable()){
            model.addAttribute("errMessage", "res.errCarAv2");
            return reservationHome(model);
        }
        if(!car.getCompany().getId().equals(empl.get(0).getCompany().getId())){
            model.addAttribute("errMessage", "res.errComp" );
            return reservationHome(model);
        }
        res.setCar(car);
        
        Date datum = new java.sql.Date(utilDate.getTime());
        res.setReservedTo(datum);
        java.util.Date tempDate = new java.util.Date();
        if(tempDate.after(datum)){
            model.addAttribute("errMessage", "res.errDate2");
            return reservationHome(model);
        }
        
        try {
            facade.addReservation(res);
            model.addAttribute("infoMessage", "res.created");
        } catch (Exception ex) {
            model.addAttribute("errMessage", "res.errCarAv");
        }
        
        return reservationHome(model);
    }
    
    @RequestMapping(value = "/reservationFilter")
    public String filterData(@RequestParam(value = "type1", required = false) String type1,
            @RequestParam(value = "type2", required = false) String type2,
            @RequestParam(value = "type3", required = false) String type3,
            @RequestParam(value = "type4", required = false) String type4,
            @RequestParam(value = "seats1", required = false) String seat1,
            @RequestParam(value = "seats2", required = false) String seat2,
            @RequestParam(value = "seats3", required = false) String seat3,
            @RequestParam(value = "seats4", required = false) String seat4,
            Model model) {
        int count = 0;
        if (type1 != null) {
            count++;
        }
        if (type2 != null) {
            count++;
        }
        if (type3 != null) {
            count++;
        }
        if (type4 != null) {
            count++;
        }
        String[] types = new String[count];
        if (type4 != null) {
            types[count - 1] = type4;
            count--;
        }
        if (type3 != null) {
            types[count - 1] = type3;
            count--;
        }
        if (type2 != null) {
            types[count - 1] = type2;
            count--;
        }
        if (type1 != null) {
            types[count - 1] = type1;
            count--;
        }
        if (types.length < 1) {
            types = null;
        }
        count = 0;
        if (seat1 != null) {
            count++;
        }
        if (seat2 != null) {
            count++;
        }
        if (seat3 != null) {
            count++;
        }
        if (seat4 != null) {
            count++;
        }
        int[] seats = new int[count];
        if (seat4 != null) {
            seats[count - 1] = Integer.parseInt(seat4);
            count--;
        }
        if (seat3 != null) {
            seats[count - 1] = Integer.parseInt(seat3);
            count--;
        }
        if (seat2 != null) {
            seats[count - 1] = Integer.parseInt(seat2);
            count--;
        }
        if (seat1 != null) {
            seats[count - 1] = Integer.parseInt(seat1);
            count--;
        }
        if (seats.length < 1) {
            seats = null;
        }
        RequestDTO request = new RequestDTO();
        request.setTypes(types);
        request.setNumbersOfseats(seats);
        if((types==null) && (seats==null)){
            String[] temp1 = {"combi", "sedan", "hatchback", "van"};
            request.setTypes(temp1);
            int[] temp2 = {2,4,5,7};
            request.setNumbersOfseats(temp2);
        }

        cars = new ArrayList<CarDTO>();
        List<CarDTO> tmp = facade.processRequest(request);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        List<EmployeeDTO> empl = facade.findEmployeeByUsername(name);
        for (int i = 0; i < tmp.size(); i++){
            if (tmp.get(i).getCompany().getName().equals(empl.get(0).getCompany().getName())){
                cars.add(tmp.get(i));
            }
        }
        return reservationHome(model);
        
    }
    
    @RequestMapping(value = "/reservationDelete")
    public String deleteReservation(@RequestParam(value = "id") String id,
            Model model) {
        ReservationDTO res = facade.getByID(Long.parseLong(id));
        facade.removeReservation(res);
        model.addAttribute("infoMessage", "res.removed");
        return reservationHome(model);
    }
}
